import http from '@ohos.net.http'
import promptAction from '@ohos.promptAction'
import Logger from '../util/Logger'
import { RecordData } from '@ohos.base'

const TAG: string = '[Http]'

/*
 * 网络请求
 */
class Http {
  url: string
  name: string
  extraData: Object
  options: http.HttpRequestOptions

  constructor() {
    this.url = 'http://123.249.83.149:8088'
    this.options = {
      method: http.RequestMethod.POST,
      extraData: this.extraData,
      header: { 'Content-Type': 'application/json' },
      readTimeout: 30000,
      connectTimeout: 30000
    }
  }

  setUrl(url: string) {
    this.name = url
    Logger.info(TAG, `setUrl url: ${this.url + this.name}`)
  }

  setMethod(method: string) {
    switch (method) {
      case 'GET':
        this.options.method = http.RequestMethod.GET
        break
      case 'POST':
        this.options.method = http.RequestMethod.POST
        break
      case 'PUT':
        this.options.method = http.RequestMethod.PUT
        break
      case 'DELETE':
        this.options.method = http.RequestMethod.DELETE
        break
      default:
        this.options.method = http.RequestMethod.GET
        break
    }
  }

  setExtraData(extraData: Object) {
    this.options.extraData = extraData
  }

  setOptions(option: Object) {
    this.options = option
  }

  setList(list: number[], flag: number) {
    list = []
    for (let i = 0; i < flag; i++) {
      list[i] = i
    }
    return list
  }

  setParameter(keys: string[], values: Any[]): Array<string> {
    let result = {}
    for (let i = 0; i <= keys.length - 1; i++) {
      let key = keys[i]
      let value = values[i]
      result[key] = value
    }
    Logger.info(TAG, `setParameter result: ${JSON.stringify(result)}`)
    return result
  }

  async request(): Promise<string | RecordData | ArrayBuffer> {
    let httpRequest = http.createHttp()
    let result: http.HttpResponse = await (httpRequest.request(this.url + this.name, this.options))
    Logger.info(TAG, `request: ${JSON.stringify(result)}`)
    let res: string | RecordData | ArrayBuffer = result.result
    if (result.responseCode === 200) {
      let result: http.HttpResponse | null | undefined =
        JSON.parse<http.HttpResponse>(res as string, Type.from<http.HttpResponse>())
      if (result!.code != 200) {
        promptAction.showToast({
          message: result.msg,
          duration: 2000
        })
      }
      return result
    }
    return ''
  }
}

export default new Http()